checkLogin();

map = new qq.maps.Map(document.getElementById("container"), {
    zoom: 16,
    zoomControl: false,
});

//地图相关
//计算地图全屏高度
var height = $(document).height();
$('#container').css('height',height);
var geocoder, map,mubiao, circle ,marker ,info ,lat ,lng ,address ,name,center ,nearPost ,shop_center , range_height= null;

//获取地址详细信息
var address_taile = getCache(address_key);
address_taile = JSON.parse(address_taile);
if(address_taile == undefined || address_taile == null || address_taile == ''){
    history.go(-1);
}

var latLng = address_taile.area_position;
if(!isEmpty(latLng)){
    lat = latLng.split(',')[0];
    lng = latLng.split(',')[1];
    init_shop();
}else {
    //根据已经有的地址获取经纬度
    //地址和经纬度之间进行转换服务
    geocoder = new qq.maps.Geocoder({
        //设置服务请求成功的回调函数
        complete: function (result) {
            console.log(123)
            map.setCenter(result.detail.location);
            console.log(result.detail.location)
            lat = result.detail.location.lat;
            lng = result.detail.location.lng;
            //调用初始化函数地图
            init_shop();
        },
        //若服务请求失败，则运行以下函数
        error: function () {
            mui.toast('定位失败，重新填写');
        }
    })
    //如果没有经纬度 那么 按照店铺地址获取经纬度
    if(isEmpty(address_taile.position_address)){
        geocoder.getLocation(address_taile.area_info + address_taile.address);
    }else {
        geocoder.getLocation(address_taile.position_address);
    }

}
if(isEmpty(address_taile.position_address)){
    $('#map_address').text(address_taile.area_info);
    $('#address_hidden').val(address_taile.area_info);
}else {
    $('#map_address').text(address_taile.position_address);
    $('#address_hidden').val(address_taile.position_address);
}
$('#name').val(address_taile.address);
$('#latLng').val(address_taile.area_position);
$('#userName').val(address_taile.name);
$('#mobile').val(address_taile.mobile);
$('#province_id').val(address_taile.province_id);
$('#city_id').val(address_taile.city_id);
$('#area_id').val(address_taile.area_id);
$('#area_info').val(address_taile.area_info);


//获取水店的
function init_shop() {
    //获取水票须知
    var success = function (res) {
        var info = res.data.info;
        console.log(info)
        shop_center = info.shop_position;
        range_height = info.send_area_radius * 1000;
        init();
    }

    getData(shop_info,comParams(),success);
}

function choose() {
    if(!isEmpty(nearPost)){
        $('.choose_addr_list').show();
        /*var dom = document.getElementById('choose').hasChildNodes();*/
        var dom = $('#choose').children().hasClass('address-choose');
        if(!dom){
            var html = template('choose-content',nearPost);
            $('#choose').html(html);
        }

        $('.radio').bind('click',function (e) {
            marker.setMap(null);
            info.setMap(null);
            var list = nearPost.nearPois;
            var index = parseInt(this.getAttribute('data-index'));
            var t = e.target;
            if($(t).children().hasClass('active')){

            }else {
                $('.radio').children().removeClass('active');
                $(t).children().addClass('active');
            }
            lat = list[index].latLng.lat;
            lng = list[index].latLng.lng;
            make_map(lat,lng);
            var address = list[index].address;
            var name = list[index].name;
            $('#map_address').text(address);
            $('#address_hidden').val(address);
            $('#name').val(name);
            $('#latLng').val(lat+','+lng);
            $('.choose_addr_list').hide();
            var user_add = list[index].latLng;
            if(!isEmpty(shop_center) && !isEmpty(range_height) && range_height >0){
                //判断是否在配送范围
                rangeLatLng(user_add);
            }
        })
    }else {
        mui.toast('请选择地址');
    }
}

$('.chacha').bind('click',function () {
    $('.choose_addr_list').hide();
})


function init() {
    center = new qq.maps.LatLng(lat, lng);
    map.setCenter(center);
    marker = new qq.maps.Marker({
        //设置Marker的位置坐标
        position: center,
        //设置显示Marker的地图
        map: map
    });
    //设置Marker是否可以被拖拽，为true时可拖拽，false时不可拖拽，默认属性为false
    marker.setDraggable(false);
    //添加信息窗口
    info = new qq.maps.InfoWindow({
        map: map
    });
    //获取标记的可拖动属性
    info.open();
    info.setContent('<p style="color:  #25bdef">送水到这里</p>');
    info.setPosition(marker.getPosition());


    //点击地图获取点击地点的地址和坐标
    geocoder = new qq.maps.Geocoder({
        complete : function(result){
            var list = result.detail.nearPois;
            nearPost = result.detail;
            console.log(nearPost)
            province = nearPost.addressComponents.province;
            city = nearPost.addressComponents.city;
            area = nearPost.addressComponents.district;
            getAddressCode(province,city,area);
            $('.choose_addr_list').show();
            var html = template('choose-content',result.detail);
            $('#choose').html(html);

            $('.radio').bind('click',function (e) {
                marker.setMap(null);
                info.setMap(null);
                $('.choose_addr_list').hide();
                var index = parseInt(this.getAttribute('data-index'));
                var t = e.target;
                if($(t).children().hasClass('active')){
                    $('.radio').children().removeClass('active');
                    $(t).children().addClass('active');
                }
                lat = list[index].latLng.lat;
                lng = list[index].latLng.lng;
                make_map(lat,lng);
                var address = list[index].address;
                var name = list[index].name;
                $('#map_address').text(address);
                $('#address_hidden').val(address);
                $('#name').val(name);
                $('#latLng').val(lat+','+lng);
                var user_add = list[index].latLng;
                if(!isEmpty(shop_center) && !isEmpty(range_height) && range_height >0){
                    //判断是否在配送范围
                    rangeLatLng(user_add);
                }
            })

            $('.getAddress').bind('click',function () {
                var id = this.getAttribute('data-id');
                console.log(id)
                for(var i=0;i<add_list.length;i++){
                    if(add_list[i].id == id){
                        //弹出所输入坐标后对比中心坐标 看是否在配送范围
                        mubiao = new qq.maps.LatLng(add_list[i].latLng.lat,add_list[i].latLng.lng);

                        var length = qq.maps.geometry.spherical.computeDistanceBetween(center, mubiao);
                        console.log(length)
                        if(length > range_height){
                            alert("超出配送范围")
                        }else {
                            alert("配送范围内")
                        }
                        alert('您选中地址为：'+add_list[i].address + add_list[i].name);
                    }
                }
            })
        }
    });

    //绑定单击事件添加参数
    qq.maps.event.addListener(map, 'click', function(event) {
        marker.setMap(null);
        info.setMap(null);

        //根据获取的经纬度 得到具体地址
        var latLng = new qq.maps.LatLng(event.latLng.getLat(), event.latLng.getLng());
        geocoder.getAddress(latLng);
    });
}

function make_map(lat,lng) {
    center = new qq.maps.LatLng(lat, lng);
    map.setCenter(center);
    marker = new qq.maps.Marker({
        map:map,
        position: center
    });
    info = new qq.maps.InfoWindow({
        map: map
    });
    //获取标记的可拖动属性
    info.open();
    info.setContent('<p style="color:  #25bdef">送水到这里</p>');
    info.setPosition(marker.getPosition());
}

function codeLatLng(lat,lng) {
    //获取输入框的经纬度
    var latLng = new qq.maps.LatLng(lat, lng);
    //对指定经纬度进行解析
    geocoder.getAddress(latLng);
    //设置服务请求成功的回调函数
    geocoder.setComplete(function(result) {
        console.log(result)
        nearPost = result.detail;
    });
    //若服务请求失败，则运行以下函数
    geocoder.setError(function() {
        return null;
    });
}

function codeAddress(infos) {
    if(isEmpty(infos)){
        return;
    }
    //根据已经有的地址获取经纬度
    //地址和经纬度之间进行转换服务
    geocoder = new qq.maps.Geocoder({
        //设置服务请求成功的回调函数
        complete: function (result) {
            console.log(result.detail.location)
            lat = result.detail.location.lat;
            lng = result.detail.location.lng;
            //根据获取的经纬度得到附近的地点
            codeLatLng(lat,lng);
            //获取输入框的经纬度
            var latLng = new qq.maps.LatLng(lat, lng);
            //对指定经纬度进行解析
            geocoder.getAddress(latLng);
            //设置服务请求成功的回调函数
            geocoder.setComplete(function(result) {
                console.log(result)
                nearPost = result.detail;
                var list = nearPost.nearPois;
                $('.choose_addr_list').show();
                var html = template('choose-content',result.detail);
                $('#choose').html(html);
                $('.radio').bind('click',function (e) {
                    $('.hidden_text').show();
                    $('.show_text').hide();
                    marker.setMap(null);
                    info.setMap(null);
                    $('.choose_addr_list').hide();
                    var index = parseInt(this.getAttribute('data-index'));
                    var t = e.target;
                    if($(t).children().hasClass('active')){
                        $('.radio').children().removeClass('active');
                        $(t).children().addClass('active');
                    }
                    lat = list[index].latLng.lat;
                    lng = list[index].latLng.lng;
                    make_map(lat,lng);
                    var address = list[index].address;
                    var name = list[index].name;
                    $('#map_address').text(address);
                    $('#address_hidden').val(address);
                    $('#name').val(name);
                    $('#latLng').val(lat+','+lng);
                    var user_add = list[index].latLng;
                    if(!isEmpty(shop_center) && !isEmpty(range_height) && range_height >0){
                        //判断是否在配送范围
                        rangeLatLng(user_add);
                    }
                })
            });
            //若服务请求失败，则运行以下函数
            geocoder.setError(function() {
                return null;
            });
        },
        //若服务请求失败，则运行以下函数
        error: function () {
            mui.toast('定位失败，请填写如 xx 市 xx 区 xxx');
        }
    });
    //如果没有经纬度 那么 按照店铺地址获取经纬度
    geocoder.getLocation(infos);
}

//判断是否在配送范围
//user_add 表示用户所选地址即中心位置（lat，lng）
function rangeLatLng(user_add) {
    //弹出所输入坐标后对比中心坐标 看是否在配送范围
    var lat = shop_center.split(',')[0];
    var lng = shop_center.split(',')[1];
    var shop_add = new qq.maps.LatLng(lat,lng);

    var length = qq.maps.geometry.spherical.computeDistanceBetween(shop_add, user_add);
    console.log(length)
    if(length >range_height){
        mui.toast('超出配送范围');
        /* $('.add-btn').attr('disable','true');*/
        $(".add-btn").attr("disabled",'ture');
    }else {
        mui.toast("配送范围内")
        $(".add-btn").removeAttr("disabled");
    }
}

//根据省市区 获取对应编码
function getAddressCode(provice,city,area) {
    if(isEmpty(area)){
        area = '江夏区';
    }
    var area_info = provice + ' '+ city + ' '+area;
    $('#area_info').val(area_info);
    console.log(cityData3)
    if(isEmpty(cityData3) || cityData3.length <=0){
        return;
    }
    for(var i=0;i<cityData3.length;i++){
        var data = cityData3[i];
        if(data.text == provice){
            $('#province_id').val(data.value);
            var children = data.children;
            if(!isEmpty(children) && children.length > 0){
                for(var j = 0;j<children.length;j++){
                    if(children[j].text == city){
                        $('#city_id').val(children[j].value);
                        children = children[j].children;
                        if(!isEmpty(children) && children.length > 0){
                            for(var m =0;m<children.length;m++){
                                if(children[m].text == area){
                                    $('#area_id').val(children[m].value);
                                    break;
                                }
                            }
                        }
                        break;
                    }
                }
            }
            break;
        }
    }
}

var id = address_taile.id;
//验证表单并处理登录交互
var ajaxOption = {
    url: address_edit,
    method: 'POST',
    data:combineParams({id:id}),
    success: function (res) {
        setTimeout(function () {
            locationReplace('address.html');
        },2000);
    }
};

checkform($('#myForm'), ajaxOption);

var is_mobile = function(e) {
    var status = true;
    if (!(/^1\d{10}$/.test( $(e).val()))){
        status = false;
    }
    return {
        status: status, // or false
        message: '请填写正确的手机号'
    };
}

$('.search_i').bind('click',function () {
    /*$('.search_choosed').hide();*/
    var search_address = $('.search_address').val();
    if(isEmpty(search_address)){
        return;
    }
    codeAddress(search_address);
    $('.search_address').val('');
})

$('.search_i_black').bind('click',function () {
    $('.search_choosed').show();
})

$('.search_cha').bind('click',function () {
    $('.hidden_text').hide();
    $('.show_text').show();
})

$('.show_text').bind('click',function () {
    $('.hidden_text').show();
    $('.show_text').hide();
})

